#include <string.h>
#include <openssl/evp.h>
int base64encode(char* szSrc, char* szDst, size_t nSrcLen, size_t& nDstLen);
int base64decode(char* szSrc, char* szDst, size_t nSrcLen, size_t& nDstLen);

int main(int argc, char* argv[])
{
  char src[] = "hellowsafdasfdasfdasfdhasfldaskfdaslf";
  char dst[512] = {0};
  size_t len = 0;
  base64encode(src, dst, strlen(src), len);
  printf("[%s] len = [%d] strlen = [%d]\n", dst, len, strlen(dst));

  char ddst[512] = {0};
  base64decode(dst, ddst, strlen(dst), len);
  printf("[%s] len = [%d] strlen = [%d]\n", ddst, len, strlen(ddst));
  return 0;
}
int base64encode(char* szSrc, char* szDst, size_t nSrcLen, size_t& nDstLen)
{
  unsigned char uszSrc[1024] = {0};
  unsigned char uszDst[1024] = {0};
  memcpy(uszSrc, szSrc, nSrcLen);
  int total = 0;
  int dstlen = 0;

  EVP_ENCODE_CTX  ectx;
  EVP_EncodeInit(&ectx);
  EVP_EncodeUpdate(&ectx, uszDst, &dstlen, uszSrc, nSrcLen);
  total += dstlen;
  EVP_EncodeFinal(&ectx, uszDst + total, &dstlen);
  total += dstlen;

  memcpy(szDst, uszDst, total);
  nDstLen = total;
  return 0;
}

int base64decode(char* szSrc, char* szDst, size_t nSrcLen, size_t& nDstLen)
{
  unsigned char uszSrc[1024] = {0};
  unsigned char uszDst[1024] = {0};
  memcpy(uszSrc, szSrc, nSrcLen);

  int total = 0;
  int dstlen = 0;

  EVP_ENCODE_CTX  dctx;
  EVP_DecodeInit(&dctx);
  int ret=EVP_DecodeUpdate(&dctx, uszDst, &dstlen, uszSrc, nSrcLen);

  if(ret<0)
  {
    printf("EVP_DecodeUpdate err!\n");
    return -1;
  }

  total += dstlen;
  ret = EVP_DecodeFinal(&dctx, uszDst, &dstlen);
  total += dstlen;

  memcpy(szDst, uszDst, total);
  nDstLen = total;
  return 0;
}
